package com.dingding.baseservice.payment.wechat;

import java.util.Date;

import org.apache.log4j.Logger;

import com.dingding.bean.api.wechat.SecondSign;
import com.dingding.bean.api.wechat.WechatPayOrderQueryRequest;
import com.dingding.bean.api.wechat.WechatPayOrderQueryResponse;
import com.dingding.bean.api.wechat.WechatPayOrderRequest;
import com.dingding.bean.api.wechat.WechatPayOrderResponse;
import com.dingding.common.core.util.HttpTool;
import com.dingding.common.core.util.MD5Util;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.UrlMaker;
import com.dingding.common.core.util.XMLParse;

public class WechatPayApi {
	
	private static Logger log = Logger.getLogger(WechatPayApi.class);
	
	/**
	 * @Title: placeAnOrder
	 * @Description:微信下单
	 * 				当用户在app下单并选择微信支付时，
	 * 				服务器向微信支付系统发起初次请求，生成订单
	 * @param request 向微信服务器发送的请求内容
	 * @param WechatPayOrderResponse 请求结果
	 * @author fengshuonan
	 * @throws
	 */
	public WechatPayOrderResponse placeAnOrder(WechatPayOrderRequest request){
		
		//获取请求信息，并转化成xml信息
		String requestXml = XMLParse.toXML(request);
		
		//发起http post请求,并获取请求结果
		String responseXml = HttpTool.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);
		
		log.info("微信返回的数据为：" + responseXml);
		
		//如果接收到的请求结果为空
		if(ToolUtil.isBlank(responseXml)){
			return null;
		}
		
		//把xml信息转化成bean
		WechatPayOrderResponse response = XMLParse.toObject(responseXml, WechatPayOrderResponse.class);
		
		return response;
	}
	
	
	/**
	 * @Title: orderQuery
	 * @Description: 向微信服务器发送请求，查询订单支付结果是成功
	 * @param request 查询订单请求封装
	 * @author fengshuonan
	 * @return WechatPayOrderResponse 返回结果封装
	 * @throws
	 */
	public WechatPayOrderQueryResponse orderQuery(WechatPayOrderQueryRequest request){
		
		//获取请求信息，并转化成xml信息
		String requestXml = XMLParse.toXML(request);
		
		//发起http post请求,并获取请求结果
		String responseXml = HttpTool.postXml("https://api.mch.weixin.qq.com/pay/orderquery", requestXml);
	
		//如果接收到的请求结果为空
		if(ToolUtil.isBlank(responseXml)){
			return null;
		}
		
		//把xml信息转化成bean
		WechatPayOrderQueryResponse response = XMLParse.toObject(responseXml, WechatPayOrderQueryResponse.class);
		
		return response;
	}
	
	/**
	 * @Title: createAppPayRequest
	 * @Description: 创建一个app微信支付请求bean
	 * @param orderId 订单id
	 * @param totalFee 总金额（单位：分） 
	 * @author fengshuonan
	 * @return WechatPayOrderRequest
	 * @throws
	 */
	public static WechatPayOrderRequest createAppPayRequest(String orderId,int totalFee,String ip){
		
		WechatPayOrderRequest payRequest = new WechatPayOrderRequest();
		
		payRequest.setAppid("wx8b6d01f28792414a");//叮叮搭车应用的appid
		payRequest.setMch_id("1316301901");//叮叮搭车应用商户号
		payRequest.setNonce_str(ToolUtil.randomLenStr(20));//生成20位随机码
		payRequest.setBody("搭车费用");//简要描述   
		payRequest.setOut_trade_no(orderId);//商户订单号
		payRequest.setTotal_fee(totalFee);//总金额
		payRequest.setSpbill_create_ip(ip);//app端用户的ip
		payRequest.setNotify_url(UrlMaker.getWechatPayNotifyUrl());//微信响应服务器的地址
		payRequest.setTrade_type("APP");//交易类型 app方式
		
		//生成签名
		String apiSec = "j5axbIfMSZjsiEGAScGMCUhp5kO2Oqaj";//API安全秘钥 
		String stringSignTemp = ToolUtil.lexSortBean(payRequest, WechatPayOrderRequest.class) + "key=" + apiSec;
		
		log.info("统一下单的序列为：" + stringSignTemp);
		
		String sign = MD5Util.md5Encrypt(stringSignTemp).toUpperCase();
		payRequest.setSign(sign);
		
		log.info("统一下单的签名为：" + sign);
		
		return payRequest;
	}
	
	
	/**
	 * @Title: createWechatPayQueryRequest
	 * @Description:创建微信支付查询支付结果请求bean
	 * @param 服务器本地的订单号
	 * @author fengshuonan
	 * @return WechatPayOrderQueryRequest
	 * @throws
	 */
	public static WechatPayOrderQueryRequest createWechatPayQueryRequest(String orderId){
		
		if(ToolUtil.isBlank(orderId)){
			return null;
		}
		
		WechatPayOrderQueryRequest request = new WechatPayOrderQueryRequest();
		request.setAppid("wx8b6d01f28792414a");//叮叮搭车应用的appid
		request.setMch_id("1316301901");//叮叮搭车应用商户号
		request.setNonce_str(ToolUtil.randomLenStr(20));//生成20位随机码
		request.setOut_trade_no(orderId);
		
		//生成签名
		String apiSec = "j5axbIfMSZjsiEGAScGMCUhp5kO2Oqaj";//API安全秘钥 
		String stringSignTemp = ToolUtil.lexSortBean(request, WechatPayOrderQueryRequest.class) + "key=" + apiSec;
		String sign = MD5Util.md5Encrypt(stringSignTemp).toUpperCase();
		request.setSign(sign);
		
		return request;
	}
	
	
	/**
	 * @Title: getSecondSign
	 * @Description: 获取二次签名
	 * @param secondSign 二次签名所需要的参数
	 * @author fengshuonan
	 * @return String 
	 * @throws
	 */
	public static SecondSign getSecondSign(String prepayId,String nonceStr){
		
		SecondSign secondSign = new SecondSign();
		secondSign.setAppid("wx8b6d01f28792414a");
		secondSign.setPartnerid("1316301901");
		secondSign.setPrepayid(prepayId);
		secondSign.setNoncestr(nonceStr);
		
		//生成秒级别的时间戳
		Long l = new Long(String.valueOf(new Date().getTime()));
		l = l/1000;
		secondSign.setTimestamp(l.toString());
		
		//生成签名
		String apiSec = "j5axbIfMSZjsiEGAScGMCUhp5kO2Oqaj";//API安全秘钥 
		String stringSignTemp = ToolUtil.lexSortBean(secondSign, SecondSign.class,"package=Sign=WXPay") + "key=" + apiSec;
		
		log.info("二次签名生生序列为：" + stringSignTemp);
		
		String sign = MD5Util.md5Encrypt(stringSignTemp).toUpperCase();
		
		secondSign.setSign(sign);
		
		return secondSign;
	}
	
}
